<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="formVisible=true">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="内容分类名" value="1"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok"/>
      </div>
    </div>
    <el-table stripe style="width: 100%"  border fit highlight-current-row ref="tableDataRef" :data="tableData" :key="key">
      <el-table-column v-if="colData[0].istrue" min-width="50" align="center" prop="id" label="ID"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="name" label="分类名称"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="50" align="center" prop="contentNum" label="内容数量"> </el-table-column>
      <el-table-column v-if="false"  min-width="100" align="center" prop="batch" label="分发批次" >
        <template slot-scope="scope">
          <div v-if="scope.row.batch.length <= 5">
            <p v-for="(item,index) in scope.row.batch" :key="item.id" style="margin: 0;padding: 0">{{item.batch}}</p>
          </div>
          <div v-else>
            <el-popover
              placement="right"
              width="600"
              trigger="click">
              <span v-for="(item,index) in scope.row.batch" :key="item.id" style="margin: 0;padding: 0">{{item.batch}}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <el-button slot="reference" size="small">点击查看全部</el-button>
            </el-popover>
          </div>
        </template>
      </el-table-column>
      <el-table-column min-width="50" align="center" prop="sort" label="排序"></el-table-column>
      <el-table-column v-if="false" min-width="80" align="center" prop="operates" label="分发子账号">
        <template slot-scope="scope">
          <p v-for="(item,index) in scope.row.operates" :key="item.id"  style="margin: 0;padding: 0">{{item.username}}</p>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[5].istrue"  min-width="100" align="center" prop="type" label="关联文件性质">
        <template slot-scope="scope">
          <p v-for="(item,index) in scope.row.type" :key="index" style="margin: 0;padding: 0">
            <span v-show="item==1">视频</span>
            <span v-show="item==2">音频</span>
            <span v-show="item==3">文档</span>
            <span v-show="item==4">图片</span>
           </p>
        </template>
      </el-table-column>
      <el-table-column min-width="100" align="center" prop="icon" label="图标">
        <template slot-scope="scope">
          <el-image  style="width: 80px; height: 80px"  :src="scope.row.icon" fit="fill"></el-image>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[6].istrue"  min-width="100" align="center" prop="admin_name" label="创建者"></el-table-column>

      <el-table-column v-if="colData[7].istrue" min-width="140" align="center" prop="send_time" label="创建时间">
          <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column v-if="colData[8].istrue" min-width="140" align="center" prop="send_time" label="修改时间">
        <template slot-scope="scope">{{scope.row.update_time| newDate}}</template>
      </el-table-column>
      <el-table-column  label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="openEdit(scope.row)">编辑</el-button>
            <el-button size="mini" @click="delContent(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 添加弹窗 -->
    <el-dialog title="添加分类" :visible.sync="formVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="40%" @close="addFormclose">
      <el-form :model="addForm"  ref="ruleForm" :rules="rules" class="diolog_adapt" style="width: 600px" >
        <el-form-item label="图标:" label-width="130px" prop="icon">
          <el-upload
            class="avatar-uploader"
            action
            :auto-upload="false"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-change="(res,file,type)=> {adImgUpload(res,file,item)}"
          >
            <img v-if="addForm.icon" :src="addForm.icon" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类名称:" label-width="130px" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入分类名称" maxlength="60"></el-input>
        </el-form-item>
        <el-form-item label="分发方式:" label-width="130px" prop="send_type" v-if="false">
          <el-radio-group v-model="addForm.send_type">
            <el-radio :label="1">批次</el-radio>
            <el-radio :label="2">子账号</el-radio>
            <el-radio :label="3">批次和子账号</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序:" label-width="130px" prop="sort">
          <el-input v-model="addForm.sort" placeholder="请输入排序 0~999" type="number" :min="0"></el-input>
        </el-form-item>
        <el-form-item label="批次:" label-width="130px" v-if="false">
          <AiSelectAllEle
            v-model="addForm.batch"
            :options="batchArr"
            :width="150"
            labelName="batch"
            valueName="id"
          />
        </el-form-item>
        <el-form-item label="子账号:" v-if="false" label-width="130px">
          <el-select v-model="addForm.childAdmin"  multiple placeholder="请选择子账号">
            <el-option
              v-for="item in childrenOption"
              :key="item.id"
              :label="item.username"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可关联文件类型:" label-width="130px" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择" multiple>
            <el-option
              v-for="item in courseTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" size="mini" round @click="editContent('ruleForm')">确 定
        </el-button>
        <el-button v-else type="primary" @click="addContentClass('ruleForm')" size="mini" round>确定</el-button>
      </div>
    </el-dialog>
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>

</template>

<script>
  import objectable from "@/utils/objectable.js";
  import dynamicTable from "@/components/DynamicTable";
  import deleteDialog from "@/components/deleteDialog";
  import tableMini from '@/utils/tableMini.js'
  import {
    getChildAdmin,
    addContentClass,
    queryContentClass,
    editContentClass, deleteContentClass
  } from "@/api/launcherMade";
  import {ossFile, ossImage} from "@/utils/ossUpload";
  import {getBatchTwo} from "@/api/equipment";
  import AiSelectAllEle from "@/components/SelectAllEle/index";

  export default {
    mixins: [tableMini],
    components: {AiSelectAllEle, dynamicTable, deleteDialog},
    data() {
      return {
        key: 1,
        colData: [], //动态控制table
        checkboxVal: ["ID", "分类名称", "内容数量", "分发批次", "分发子账号", "关联文件性质", "创建者", "创建时间", "修改时间"],
        searchTable: "",
        select: "", //搜索条件
        tableData: [],
        listQuery: {
          startSize: 1,
          pageSize: 10,
          userId: localStorage.getItem("ID"),
        },
        addForm: {
          name: '',
          type: [],
          send_type: 1,
          childAdmin: [],
          batch: [],
          sort: 0,
          icon: ''
        },
        formVisible: false,
        rules: {
          name: [{required: true, message: '请输入分类名称', trigger: 'blur'}],
          type: [{ required: true, message: '请选择可关联文件性质', trigger: 'change' }],
          // send_type: [{ required: true, message: '请选择分发方式', trigger: 'change' }],
          sort: [{required:true, message: '请输入排序 0~999', trigger: 'blur'}],
          icon: [{required:true, message: '请先传分类图标', trigger: 'blur'}],
        },
        editSubjects: false,
        deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
        courseTypeOptions: [{label:'视频',value:1},{label: '音频',value: 2}, {label: '文档',value: 3}, {label: '图片', value: 4}],
        childrenOption: [],  //子账号可选框
        batchArr: [],
        optionsList:  [{label: "商品1", value: 1}]
      }
    },
    created() {
      this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
      this.getContentTableData()
      this.getBatchTwo()
      this.getChildAdmin()
    },
    methods: {
      Refresh() {
        this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), name: undefined}
        this.getContentTableData()
      },
      getBatchTwo() {
        getBatchTwo({ userId: localStorage.getItem("ID") }).then(res => {
          this.batchArr = res.data
        }).catch(err => {
          this.batchArr = []
        })
      },
      getChildAdmin() {
        getChildAdmin({ userId: localStorage.getItem("ID") }).then(res => {
          this.childrenOption = res.data
        }).catch(err => {
          this.childrenOption = []
        })
      },
      //搜索,1:课程名称
      idnameSearch() {
        if (!this.select) return this.$message.warning("请先选择查询条件");
        this.listQuery.startSize = 1
        this.listQuery.pageSize = 10
        switch (this.select) {
          case '1':
            this.listQuery.name = this.searchTable
            this.getContentTableData();
            break;
        }
      },
      openEdit(row) {
        this.formVisible = true
        this.editSubjects=true
        this.addForm = {
          name: row.name,
          type: row.type,
          send_type: row.send_type,
          childAdmin: row.childAdmin,
          batch: row.batchArr,
          icon: row.icon,
          id: row.id,
          sort: row.sort
        }
      },
      addContentClass(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let addForm = JSON.parse(JSON.stringify(this.addForm))
            addForm.last_ip = sessionStorage.getItem("Ip")
            addForm.userId = localStorage.getItem("ID")
            addContentClass(addForm).then(res => {
              if(res.code==200){
                this.$message.success(res.msg)
                this.getContentTableData()
              }
              this.formVisible = false
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      getContentTableData() {
        queryContentClass(this.listQuery).then(res => {
          if(res.code==200){
            this.tableData = res.data
            this.total = res.total
          }else{
            this.$message.error(this.res.msg)
          }
        }).catch(err => {
          this.tableData = []
          this.total = 0
        })
      },
      editContent(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let editForm = JSON.parse(JSON.stringify(this.addForm))
            editForm.last_ip = sessionStorage.getItem("Ip")
            editForm.userId = localStorage.getItem("ID")
            editContentClass(editForm).then(res => {
              this.$message.success(res.msg)
              this.formVisible = false
              this.getContentTableData()
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      delContent(id) {
        this.deleteDialogs.show = true
        this.deleteDialogs.deleteId = id
      },
      //删除按钮事件
      deleteEvents() {
        let params = {
          userId: localStorage.getItem("ID"),
          last_ip: sessionStorage.getItem("Ip"),
          id: this.deleteDialogs.deleteId,
        }
        deleteContentClass(params).then(res => {
          if(res.code==200){
            this.$message.success(res.msg)
          }else{
            this.$message.error(res.msg)
          }
          this.getContentTableData()
        }).catch(err => {
          console.log("请求失败", err)
        })
      },
      //分页
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getContentTableData()
      },
      handleCurrentChange(val) {
        this.listQuery.startSize = val
        this.getContentTableData()
      },
      //下拉动态table子组件
      alterCheckbok(key, conte) {
        this.key = key;
        this.colData.filter(i => {
          if (conte.indexOf(i.title) != -1) {
            i.istrue = false;
            this.$nextTick(() => {
              this.$refs.tableDataRef.doLayout();
            });
          } else {
            i.istrue = true;
            this.$nextTick(() => {
              this.$refs.tableDataRef.doLayout();
            });
          }
        });
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //图片上传
      adImgUpload(res) {
        ossImage(res.raw,res.name).then(res => {//图片上传
          this.addForm.icon = res
        }).catch(err => {
          this.$message.error("图标上传失败")
        })
      },
      //编辑添加表单关闭事件
      addFormclose() {
        this.editSubjects=false
        this.$nextTick(() => {
          this.addForm = this.$options.data().addForm
        })
      },
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
</style>


